package br.com.viewcar.web.bean;

import java.io.Serializable;
import java.util.List;

import br.com.viewcar.service.BaseService;

public abstract class EntityBean<Id extends Serializable, Entity extends Serializable> extends CrudStateBean {

	protected abstract BaseService<Id, Entity> retrieveEntityService();
	protected abstract Id retrieveEntityId(Entity entity);
	protected abstract Entity createNewEntity();
	protected List<Entity> entities;
	protected Entity entity;
	protected String filter;

	public String close() {
		entities = null;
		this.entity = null;
		this.filter = null;
		return super.closePopup();
	}

	public String getFilter() {
		return filter;
	}

	public void setFilter(String filter) {
		this.filter = filter;
	}

	public Entity getEntity() {
		if (this.entity == null) {
			this.entity = createNewEntity();
		}
		return this.entity;
	}

	public void setEntity(Entity entity) {
		this.entity = entity;
	}

	public List<Entity> getEntities() {
		return (List<Entity>) entities;
	}

	public Integer getEntitiesSize() {
		return entities == null ? -1 : entities.size();
	}

	public String prepareSave() {
		this.entity = createNewEntity();
		openPopup();
		return super.prepareSave();
    }

	public String prepareSaveMontarRota() {
		this.entity = createNewEntity();
		openPopup();
		return super.prepareSaveMontarRota();
    }

	public String prepareSaveGenericRota() {
		this.entity = createNewEntity();
		openPopup();
		return super.prepareSaveGenericRota();
    }

	public String prepareSaveImportarPonto() {
		this.entity = createNewEntity();
		openPopup();
		return super.prepareSaveImportarPonto();
    }

	public String prepareSaveImportarArea() {
		this.entity = createNewEntity();
		openPopup();
		return super.prepareSaveImportarArea();
    }

    public String save() {
    	retrieveEntityService().save(this.entity);
    	openPopup();
    	return super.save();
    }

	public String prepareUpdate() {
		this.entity = retrieveEntityService().retrieve(retrieveEntityId(this.entity));
		openPopup();
		return super.prepareUpdate();
	}

	public String prepareDelete() {
		this.entity = retrieveEntityService().retrieve(retrieveEntityId(this.entity));
		openPopup();
		return super.prepareDelete();
	}

    public String update() {
    	retrieveEntityService().update(this.entity);
    	openPopup();
    	return super.update();
    }

    public String delete() {
		Id id = retrieveEntityId(this.entity);
		retrieveEntityService().delete(id);
		openPopup();
    	return super.delete();
    }

    public String search() {
    	entities = retrieveEntityService().retrieveAll();
    	entities = retrieveEntityService().filter(entities, this.filter);
    	openPopup();
    	return super.search();
    }

    public String populate() {
    	return SUCCESS;
    }
}